﻿using Core.ApiClient.App_Code.Swagger_Attribute;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Core.ApiClient
{
    public static class DIRegisterSwagger
    {
        /// <summary>
         /// 注册数据库服务
         /// </summary>
         /// <param name="services"></param>
         /// <returns></returns>
        public static IServiceCollection AddSwaggerService(this IServiceCollection services)
        {
            services.AddSwaggerGen(c =>
            {
                //c.SwaggerDoc("v1", new Info { Title = "Itool Api", Version = "v1" });

                typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
                {
                    c.SwaggerDoc(version, new Info
                    {
                        Version = version,
                        Title = $"Itool Api"
                    });
                });

                var basePath = AppContext.BaseDirectory;

                var xmlPath = Path.Combine(basePath, "Swagger.xml");

                c.OperationFilter<AssignOperationVendorExtensions>();
                c.DocumentFilter<ApplyTagDescriptions>();
                c.IncludeXmlComments(xmlPath);


            });

            return services;
        }


        /// <summary>
        /// 注册 [Swagger] API DOC
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder RegisterSwagger(this IApplicationBuilder app)
        {
            app.UseSwagger(c =>
            {
                c.PreSerializeFilters.Add((swagger, httpReq) => swagger.Host = httpReq.Host.Value);
            });

            app.UseHSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs"); });

            return app;
        }
    }
}
